<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表 -->
      <el-table :data="roleList" border stripe>
        <el-table-column type="expand"> <!-- 展开列 -->
          <template slot-scope="scope">
            <el-row :class="['role-expand', 'bdBottom']" v-for="item1 in scope.row.children" :key="item1.id">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item1.id)">{{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级三级权限 -->
              <el-col :span="19">
                <!-- for循环嵌套渲染二级权限 -->
                <el-row :class="[i2==0 ? '': 'bdTop', 'vcenter']" v-for="(item2, i2) in item1.children" :key="item2.id">
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightById(scope.row, item2.id)">{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag type="info" v-for="item3 in item2.children" :key="item3.id" closable @close="removeRightById(scope.row, item3.id)">{{ item3.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-edit"></el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeUserById(scope.row)"></el-button>

            <el-tooltip content="分配权限" placement="top" :enterable="false">
              <el-button type="warning" size="mini" icon="el-icon-setting" @click="showSetRightDialog(scope.row)"></el-button>
            </el-tooltip>

          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="showSetRightDialogClosed"
      >
      <!-- 树形控件 -->
      <el-tree 
      :data="rightList" 
      :props="treeProps" 
      show-checkbox 
      node-key="id" 
      default-expand-all
      :default-checked-keys="defKeys"
      ref="treeRef"
      ></el-tree> <!-- 
        show-checkbox节点是否可被选择 
        node-key 每个树节点用来作为唯一标识的属性，整棵树应该是唯一的 
        default-expand-all default-expand-all
        default-checked-keys 默认勾选的节点的 key 的数组
      -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRight">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
export default {
  data() {
    return {
      rightList: [],
      roleList: [],
      setRightDialogVisible: false, // 控制分配权限对话框显示隐藏
      treeProps: {
        label: 'authName',
        children: 'children'
      },  // 树形控件的属性绑定对象
      defKeys: [],  // 默认选中节点id数组
      roleId: {}, // 当前即将分配权限的角色id      
    }
  },
  created() {
    this.getRoleList();
  },
  methods: {
    async getRoleList() {
      const {data: res} = await this.$http.get('roles');
      if(res.meta.status != 200) {
        return this.$message.error('获取角色列表失败');
      } else {
        this.roleList = res.data;
      }
    },
    async removeRightById(role, rightid) { // 根据id删除对应权限
      // 弹窗确认是否删除
      const confirmResult = await this.$confirm('此操作将删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err);

      if(confirmResult != 'confirm') {
        this.$message.info('用户取消删除');
      } else {
        // console.log(roleid);
        const {data: res} = await this.$http.delete(`roles/${role.id}/rights/${rightid}`)
        if(res.meta.status != 200) {
          this.$message.success('删除权限失败');
        } else {
          this.$message.success('删除权限成功');
          // this.getRoleList(); // 该操作会重新渲染，展开列合并
          role.children = res.data;
        }
      }
    },

    async showSetRightDialog(role) {  // 展示分配权限对话框
      this.roleId = role.id; // allotRight方法不能获取角色id，这里设置角色id传递给allotRight方法使用
      // 获取所有权限数据
      this.setRightDialogVisible = true;
      const {data: res} = await this.$http.get('rights/tree');
      if(res.meta.status !== 200) {
        return this.$message.error('获取所有权限失败');
      } else {
        this.rightList = res.data;
        // 递归获取三级节点id
        this.getLeafKeys(role, this.defKeys);
      }
    },
    getLeafKeys(node, arr) { // 通过递归形式获取角色下所有三级权限id，保存到defKeys
      if(!node.children) {  // 如果node不包含children属性就是三级节点
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr);
      })
    },
    showSetRightDialogClosed() {  // 监听分配权限对话框关闭事件
      this.defKeys = []
    },
    async allotRight() {  // 点击为角色分配权限
      const keys = [   // 获取所有已选中id节点的数组
        ...this.$refs.treeRef.getCheckedKeys(),   // getCheckedKeys 若节点可被选择（即 show-checkbox 为 true），则返回目前被选中的节点的 key 所组成的数组
        ...this.$refs.treeRef.getHalfCheckedKeys()  // getHalfCheckedKeys 若节点可被选择（即 show-checkbox 为 true），则返回目前半选中的节点的 key 所组成的数组
      ];
      // console.log(keys);
      const idStr = keys.join(',');
      const {data: res} = await this.$http.post(`roles/${this.roleId}/rights`, {rids: idStr});
      if(res.meta.status !== 200) {
        this.$message.error('分配权限失败');
      } else {
        this.$message.success('分配权限成功');
        this.getRoleList();
        this.setRightDialogVisible = false;
      }
    },
  }
}
</script>
<style lang="less" scoped>
  .role-expand{width: 90%; margin: 0 auto;}
  .el-tag{margin: 7px;}
  .bdTop{border-top: 1px solid #eee;}
  .bdBottom{border-bottom: 1px solid #eee;}
  .bdBottomNone{border-bottom: none;}
  .vcenter{display: flex; align-items: center;}
</style>